<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      body {
        height: 100vh;
        width: 100vw;
        background-color: #12a182;
      }
      main {
        background-color: rgba(81, 196, 211, 0.5);
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 600px;
        height: 300px;
        /* padding: 50px 100px; */
      }
      div{
          height: 50px;
          margin-bottom: 10px;
      }
      input {
          height: 100%;
          /* 管理内部输入文本 */
        /* padding-bottom: 6px;
        padding-top: 6px;
        padding-left: 10px;
        padding-right: 40px; */
        font-size: 20px;
        /* margin-bottom: 10px; */
        outline: none;
        /* border: none; */
        box-sizing: border-box;
      }
      .error {
        border: 1px solid #ec2c64;
      }
    </style>
  </head>
  <body>
    <main>
        <div>
            <input type="text" validate rule="max:12,min:3" />
        </div>
      <div>
        <input type="text" validate rule="max:3,isNumber" />
      </div>
      
    </main>
  </body>
  <script>
    // 表单验证组件的代理工厂
    "use strict";
    class Validate {
      max(value, len) {
        return value.length <= len;
      }
      min(value, len) {
        return value.length >= len;
      }
      isNumber(value) {
        return /^\d+$/.test(value);
      }
    }
    let validate = new Validate();
    console.log(validate.max("abc", 2));

    function ProxyFactory(target) {
      return new Proxy(target, {
        get(target, key) {
          return target[key];
        },
        set(target, key, el) {
          const rule = el.getAttribute("rule");
          let state = rule.split(",").every((rule) => {
            const info = rule.split(":");
            return validate[info[0]](el.value, info[1]);
          });
            console.log(state);
          el.classList[state ? "remove" : "add"]("error");
          return true;
        },
      });
    }
    const proxy = ProxyFactory(document.querySelectorAll("[validate]"));
    proxy.forEach((item, i) => {
      item.addEventListener("keyup", function () {
        proxy[i] = this;
      });
    });
  </script>
</html>
